/*
* @Author: AskMeWhy
* @Date:   2020-05-22 09:10:37
 * @Last Modified by: AskMeWhy
 * @Last Modified time: 2021-01-14 17:20:38
*/
const app = getApp();

const { merge, isObject, isEmptyObject, debounce } = app._require("utils/index");
import { resourceSettingTable } from '../common/resource.config.js';
import { staticUrl } from "../services/config.js";
export default {
    data: {
        editorInstances: {},
        resourceId: "",
        uploadImageProps: {
            dir: "file/image/resource/",
            suffix: "png",
            num: 10
        },
        uploadVideoProps: {
            dir: "file/video/resource/",
            suffix: "mp4",
        },
        uploadFileProps: {
            dir: "file/file/resource/",
            suffix: "",
            num: 5
        },
        actionUrl: staticUrl,
    },
    setUploadDir() {
        let routeList = this.route.split("/");
        console.log(routeList);
        this.setData({
            "uploadImageProps.dir": this.data.uploadImageProps.dir + routeList[routeList.length - 2] + "/",
            "uploadVideoProps.dir": this.data.uploadVideoProps.dir + routeList[routeList.length - 2] + "/",
            "uploadFileProps.dir": this.data.uploadFileProps.dir + routeList[routeList.length - 2] + "/"
        });
    },
    convertResourceRelationId(path = "") {
        let rsId = resourceSettingTable[path || "/" + this.route];
        if (!rsId) return false;
        this.setData({
            resourceId: rsId.id,
        });
        return rsId;
    },
    getRelationServerId() {
        let customerType = app.user.userInfo.customerType;
        return customerType === 1 || customerType === 4 ? app.user.relationServer.userId : "";
    },
    buildTypeList(list, children = "child") {
        let res = [];
        res = list.map(item => {
            let cur = {};
            cur.label = item.name;
            cur.value = item.id;
            cur.source = item;
            if (item[children] && item[children].length > 0) {
                cur.children = this.buildTypeList(item[children]);
            }
            return cur;
        });
        return res;
    },
    findIdRelation(ids, _sourceList, key = "value", _returnKey) {
        let currentValue = [];
        let sourceList = _sourceList,
            sourceKey = key,
            returnKey = _returnKey || key;
        if(!Array.isArray(ids)){
            return currentValue;
        }
        ids = ids.map(cur => {
            return isNaN(Number(cur)) ? cur : Number(cur);
        });
        console.log(ids);
        function traverseSourceList(nodes) {
            let res = [];
            for (let i = 0; i < nodes.length; i++) {
                let cur = nodes[i];
                let _keyValue = isNaN(Number(cur[sourceKey])) ? cur[sourceKey] : Number(cur[sourceKey]);
                if (ids.includes(_keyValue)) {
                    if (cur.children && cur.children.length > 0) {
                        let _res = hasChildHandler(cur.children);
                        _res.map(subRes => {
                            res.push([returnKey === "_obj_" ? cur : cur[returnKey], ...subRes]);
                        });
                    } else {
                        res.push([returnKey === "_obj_" ? cur : cur[returnKey]]);
                    }
                } else {
                    if (cur.children && cur.children.length > 0) {
                        let _res = traverseSourceList(cur.children);
                        _res.map(subRes => {
                            res.push([returnKey === "_obj_" ? cur : cur[returnKey], ...subRes]);
                        });
                    }
                }
            }
            return res;
        }
        function hasChildHandler(list) {
            let res = [];
            for (let i = 0; i < list.length; i++) {
                let cur = list[i];
                if (cur.children && cur.children.length > 0) {
                    let _res = hasChildHandler(cur.children);
                    _res.map(subRes => {
                        res.push([cur[returnKey], ...subRes]);
                    });
                } else {
                    res.push([cur[returnKey]]);
                }
            }
            return res;
        }
        currentValue = traverseSourceList(sourceList);
        return currentValue;
    },
    cascaderValueFormat2Backend(value) {
        let _res = [];
        value.map(cur => {
            _res.push(cur[cur.length - 1]);
        });
        return _res;
    },
    setModel(e) {
        const _event = e.detail.currentTarget ? e.detail : e;
        const { key } = _event.currentTarget.dataset;
        if(!key) return;
        const { value } = _event.detail;
        if (Array.isArray(key)) {
            // 只有表单填报使用
            let str = "model.";
            key.forEach((item, index) => {
                if (typeof item === "number") {
                    str += "[" + item + "]";
                } else if (index === key.length - 1 && item === "info") {
                    // 单独为定位处理
                    str += "." + item;
                } else {
                    str += item;
                }
            });
            const opt = {};
            opt[str] = value;
            this.setData(opt);
        } else {
            const keys = key.split(",");
            const opt = {};
            if (keys.length > 1) {
                keys.forEach((item, $i) => {
                    opt[`model.${item}`] = value[$i] || "";
                });
            } else {
                opt[`model.${key}`] = value;
            }
            this.setData(opt);
        }
    },
    onUploadChange(e) {
        if (e.detail.type !== "upload" && e.detail.type !== "init") {
            this.onUploadSuccess({ ...e, detail: e.detail.list });
        }
    },
    onUploadSuccess(e) {
        let { key } = e.currentTarget.dataset;
        if (Array.isArray(key)) {
            let str = "model.";
            key.forEach(item => {
                if (typeof item === "number") {
                    str += "[" + item + "]";
                } else {
                    str += item;
                }
            });
            this.setData({
                [str]: e.detail,
            });
        } else {
            let modelKey = `model.${key}`;
            this.setData({
                [modelKey]: e.detail,
            });
        }
    },
    formatResourceList(type) {
        let villagerAuthList = [
            "/pages/unpackage/village-base/index",
            "/pages/unpackage/land/index",
            "/pages/unpackage/houses/index",
            "/pages/unpackage/waters/index",
            "/pages/unpackage/traded-idle-house/index",
            // "/pages/unpackage/forest/index",
            "/pages/unpackage/mountain/index",
            "/pages/unpackage/typical-species/index",
            "/pages/unpackage/folk-object/index",
            "/pages/unpackage/village-manage/index",
            "/pages/unpackage/artisan/index",
        ];
        let _resourcePathInfoList = [];
        let customerType = type || app.user.userInfo.customerType;
        if (customerType === 2) {
            this.data.$_resourcePathInfo.forEach(cur => {
                if (cur.children && cur.children.length > 0) {
                    let _res = cur.children.filter(subCur => villagerAuthList.includes(subCur.onlyKey));
                    if (_res.length > 0) {
                        let _cur = {
                            ...cur,
                            children: _res,
                        };
                        _resourcePathInfoList.push(_cur);
                    }
                }
            });
        } else {
            _resourcePathInfoList = this.data.$_resourcePathInfo;
        }
        return _resourcePathInfoList;
    },
    formatEmpty(value, emptyValue = { obj: {}, arr: [], other: "" }) {
        const emptyList = [null, undefined, ""];
        if (Array.isArray(value)) {
            return value.length === 0 ? emptyValue.arr : value;
        } else if (isObject(value)) {
            return isEmptyObject(value) ? emptyValue.obj : value;
        } else {
            return emptyList.includes(value) ? emptyValue.other : value;
        }
    },
    validateFiled(arr = [], rule) {
        let _rule = {
            required: value => {
                let _valid = true;
                if (Array.isArray(value)) {
                    _valid = value.length !== 0;
                } else if (isObject(value)) {
                    _valid = !isEmptyObject(value);
                } else {
                    if(typeof value === "string"){
                        value = value.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, "");
                    }
                    _valid = ["", null, undefined].indexOf(value) === -1;
                }
                return _valid;
            },
            // emailMsg: "请输入正确的邮箱号",
            email: value => {
                if(!_rule.required(value)) return true;
                let reg = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/g;
                return reg.test(value);
            },
            // numMsg: "请输入数字",
            num: value => {
                if (!_rule.required(value)) return true;
                let reg = /^[0-9]+$/g;
                return reg.test(value);
            },
            // phoneMsg: "请输入正确的手机号",
            tel_phone: value => {

                if (value.length==0) return false;
                let reg = /^[1-9]{1}[0-9]{10}$/g;
                return  reg.test(value);
            },
            // alphaMsg: "请输入字母",
            alpha: value => {
                if (!_rule.required(value)) return true;
                let reg = /^[A-Za-z]+$/g;
                return reg.test(value);
            },
            isTrue:value=>{
                return value;
            }

        };
        _rule = merge(true, _rule, rule);
        let res = {
            result: true,
            msg: "",
        };
        for (let i = 0; i < arr.length; i++) {
            const cur = arr[i];
            let _isEmptyRule = isEmptyObject(cur[1] || {});
            if (_isEmptyRule) {
                continue;
            }
            for (let key in cur[1]) {
                if (!_rule[key]) {
                    console.log("不存在规则==>" + key);
                    break;
                }
                if (_rule[key] && !_rule[key](cur[0])) {
                    res.result = false;
                    res.msg = cur[1][key] || _rule[key+"Msg"];
                    break;
                }
            }
            if (!res.result) break;
        }
        return res;
    },
};
